import pymysql

connect = pymysql.connect(host='localhost', port=3306, user='root', password='root', database='ai')

def dosql(id, name):
    connect.ping(True)
    cur = connect.cursor()
    sql = "insert into test (id ,name)values (%s,%s)"
    value = (id, name)
    i = cur.execute(sql, value)
    connect.commit()
    success = "失败"
    if i:
        success = "成功"
    return {"success": success}

function_name_map={'dosql':dosql}

function_json_list = [
    {
        'name': 'dosql',
        'description': "向mysql数据库插入数据id和name",
        'parameters': {
            'type': 'object',
            'properties': {
                'id': {
                    'type': 'string',
                    'description': "插入mysql数据库的id",
                },
                'name': {
                    'type': 'string',
                    'description': "插入mysql数据库的name",
                },
            },
            'required': [
                'id',
                'name',
            ],
        },
        'responses': {
            'type': 'object',
            'properties': {
                'success': {
                    'type': 'string',
                    'description': "插入数据是否成功",
                }
            }
        }
    }
]
import erniebot

erniebot.api_type = 'aistudio'
erniebot.access_token = '从aistudio上获取你自己的'
response = erniebot.ChatCompletion.create(
    model='ernie-3.5',
    messages=[
        {
            'role': 'user',
            'content': '请先数据库插入id为5,name为JiHaiXuan',
        },
    ],
    functions=function_json_list
)
if response.is_function_response:

    function_call = response.get_result()
    print(function_call)

    use_name = function_call['name']
    func_object = function_name_map[use_name]

    use_arg = function_call['arguments']
    import json
    try:
        args = json.loads(use_arg)
        out = func_object(args['id'], args['name'])
        print(out)
    except Exception as e:
        print("arg transform exception")
        raise Exception("args transform exception") from e

